package com.spring.pick2pick;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spring.pick2pick.common.DateTime;
import com.spring.pick2pick.common.PageHandler;
import com.spring.pick2pick.common.PatternChecker;
import com.spring.pick2pick.common.Util;
import com.spring.pick2pick.dao.BetDao;
import com.spring.pick2pick.dao.CommonDao;
import com.spring.pick2pick.dao.GameDao;
import com.spring.pick2pick.dao.SportDao;
import com.spring.pick2pick.model.BetItem;
import com.spring.pick2pick.model.GameItem;

@Controller
public class GameController {
	
	@Autowired
	SportDao sportDao;
	@Autowired
	CommonDao commonDao;
	@Autowired
	GameDao gameDao;
	@Autowired
	BetDao betDao;
	
	/** 경기 리스트 목록 */
	@RequestMapping(value = "listGame", method = RequestMethod.GET)
	public String listGame(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		int page = 1;
		int size = 10;
		String pageStr = request.getParameter("page");
		
		if (pageStr != null) {
			page = Integer.parseInt(pageStr);
		}
		
		String[] where = where(model, request, response);
		
		if (where == null) {
			model.addAttribute("displayCount", gameDao.getDisplayCount(null));
			model.addAttribute("unDisplayCount", gameDao.getUnDisplayCount(null));
			model.addAttribute("list", gameDao.getGameList(page, size, null, "g.idGame DESC"));
		} else {
			model.addAttribute("displayCount", gameDao.getDisplayCount(where[0]));
			model.addAttribute("unDisplayCount", gameDao.getUnDisplayCount(where[0]));
			model.addAttribute("list", gameDao.getGameList(page, size, where[0], "g.idGame DESC"));
		}
		
		model.addAttribute("sportList", sportDao.getSportList("ASC"));
		model.addAttribute("toggle", commonDao.getCommonText("경기검색"));
		model.addAttribute("page", PageHandler.getInstance());
		model.addAttribute("now", DateTime.getInstance().getNowDateTimeString());
		
		if (where[0] != null) model.addAttribute("where", where[1]);
		
		return "game/listGame";
	}
	
	/** 경기 전시여부 변경 */
	@RequestMapping(value = "displayGame", method = RequestMethod.GET)
	public String displayGame(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		String pageStr = request.getParameter("page");
		String idStr = request.getParameter("id");
		String isDisplayStr = request.getParameter("isDisplay");
		String[] where = where(model, request, response);
		
		if (pageStr == null || idStr == null || isDisplayStr == null || pageStr.equals("") || idStr.equals("") || isDisplayStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
		} else {
			int page = Integer.parseInt(pageStr);
			int id = Integer.parseInt(idStr);
			int isDisplay = Integer.parseInt(isDisplayStr);
			
			if (isDisplay == 0) {
				isDisplay = 1;
			} else if (isDisplay == 1) {
				isDisplay = 0;
			}
			
			GameItem item = new GameItem();
			item.setIdGame(id);
			item.setIsDisplay(isDisplay);
			int result = gameDao.editDisplay(item);
			
			if (result > 0) {
				
				String html = "<!doctype html>";
				html += "<head>";
				html += "<meta charset='utf-8'>";
				html += "<script>";
				html += "alert('정상적으로 수정되었습니다.');";
				if (where[0] == null) {
					html += "location.replace('listGame?page=" + page + "');";
				} else {
					html += "location.replace('listGame?page=" + page + "&where=" + where[1] + "');";
				}
				html += "</script>";
				html += "</head>";
				html += "</html>";
				
				try {
					response.setCharacterEncoding("utf-8");
					PrintWriter out = response.getWriter();
					out.print(html);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				Util.getInstance().alertPage("전시여부 수정에 실패하였습니다.", response);
			}
			
		}
		
		return null;
	}
	
	/** 경기 추가 */
	@RequestMapping(value = "addGame", method = RequestMethod.GET)
	public String addGame(Locale locale, Model model) {
		model.addAttribute("sportList", sportDao.getSportList("ASC"));
		return "game/addGame";
	}
	
	/** 경기 추가후 리스트 */
	@RequestMapping(value = "addGameOk", method = RequestMethod.POST)
	public String addGameOk(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		String idLeagueStr = request.getParameter("idLeague");
		String leagueInfo = request.getParameter("leagueInfo").trim();
		leagueInfo = leagueInfo.replace("&", "&amp;");
		leagueInfo = leagueInfo.replace("<", "&lt;");
		leagueInfo = leagueInfo.replace(">", "&gt;");
		String idHomeTeamStr = request.getParameter("idHomeTeam");
		String idAwayTeamStr = request.getParameter("idAwayTeam");
		String gameDate = request.getParameter("gameDate").trim();
		String gameInfo = request.getParameter("gameInfo").trim();
		gameInfo = gameInfo.replace("&", "&amp;");
		gameInfo = gameInfo.replace("<", "&lt;");
		gameInfo = gameInfo.replace(">", "&gt;");
		String[] gameTypeArr = request.getParameterValues("gameType");
		
		if (idLeagueStr == null || idHomeTeamStr == null || idAwayTeamStr == null || gameDate == null ||
				idLeagueStr.equals("") || idHomeTeamStr.equals("") || idAwayTeamStr.equals("") || gameDate.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
			return null;
		}
		
		if (gameTypeArr.length < 1) {
			Util.getInstance().alertPage("경기종류를 최소한 1개이상은 선택해야 합니다.", response);
			return null;
		}
		
		gameDate = gameDate.replace(" ", "");
		gameDate = gameDate.replace("-", "");
		gameDate = gameDate.replace(":", "");
		gameDate += "00";
		
		PatternChecker checker = PatternChecker.getInstance();
		if (gameDate.length() != 14 || !checker.isNum(gameDate)) {
			Util.getInstance().alertPage("경기시간을 yyyy-mm-dd hh:mm 포맷으로 입력해주세요.", response);
			return null;
		}
		
		int idLeague = Integer.parseInt(idLeagueStr);
		int idHomeTeam = Integer.parseInt(idHomeTeamStr);
		int idAwayTeam = Integer.parseInt(idAwayTeamStr);
		
		GameItem item = new GameItem();
		item.setIdLeague(idLeague);
		item.setIdHomeTeam(idHomeTeam);
		item.setIdAwayTeam(idAwayTeam);
		item.setGameDate(gameDate);
		
		if (leagueInfo != null && !leagueInfo.equals("")) {
			item.setLeagueInfo(leagueInfo);
		}
		if (gameInfo != null && !gameInfo.equals("")) {
			item.setGameInfo(gameInfo);
		}
		
		int result = gameDao.addGame(item);
		
		if (result < 1) {
			Util.getInstance().alertPage("추가에 실패하였습니다.", response);
			return null;
		}
		
		for (int i=0; i<gameTypeArr.length; i++) {
			int gameType = 0;
			try {
				gameType = Integer.parseInt(gameTypeArr[i]);
			} catch (NumberFormatException e) {
				Util.getInstance().alertPage("파라미터 형식이 잘못되었습니다.", response);
				return null;
			}
			
			String homeRateStr = null, tieRateStr = null, awayRateStr = null, rateStr = null;
			BetItem betItem = null;
			int betResult = 0;
			switch (gameType) {
			case 1:
				homeRateStr = request.getParameter("homeRate1").trim();
				tieRateStr = request.getParameter("tieRate1").trim();
				awayRateStr = request.getParameter("awayRate1").trim();
				
				if (homeRateStr.indexOf(".") > 0) {
					int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
					if (homeRateLength > 2) {
						Util.getInstance().alertPage("승무패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
					Util.getInstance().alertPage("승무패 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (tieRateStr.indexOf(".") > 0) {
					int tieRateLength = tieRateStr.substring(tieRateStr.indexOf(".") + 1, tieRateStr.length()).length();
					if (tieRateLength > 2) {
						Util.getInstance().alertPage("승무패 무배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (tieRateStr != null && !tieRateStr.equals("") && !checker.isFloat(tieRateStr)) {
					Util.getInstance().alertPage("승무패 무배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (awayRateStr.indexOf(".") > 0) {
					int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
					if (awayRateLength > 2) {
						Util.getInstance().alertPage("승무패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
					Util.getInstance().alertPage("승무패 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betItem = new BetItem();
				
				betItem.setIdGame(result);
				betItem.setGameType(gameType);
				
				try {
					float homeRate = Float.parseFloat(homeRateStr);
					betItem.setHomeRate(homeRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("승무패 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float tieRate = Float.parseFloat(tieRateStr);
					betItem.setTieRate(tieRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("승무패 무배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float awayRate = Float.parseFloat(awayRateStr);
					betItem.setAwayRate(awayRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("승무패 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betResult = betDao.addBet(betItem);
				
				if (betResult < 1) {
					Util.getInstance().alertPage("승무패 경기 아이템추가에 실패하였습니다.", response);
					return null;
				}
				
				break;
				
			case 2:
				homeRateStr = request.getParameter("homeRate2").trim();
				awayRateStr = request.getParameter("awayRate2").trim();
				
				if (homeRateStr.indexOf(".") > 0) {
					int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
					if (homeRateLength > 2) {
						Util.getInstance().alertPage("승패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
					Util.getInstance().alertPage("승패 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (awayRateStr.indexOf(".") > 0) {
					int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
					if (awayRateLength > 2) {
						Util.getInstance().alertPage("승패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
					Util.getInstance().alertPage("승패 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betItem = new BetItem();
				
				betItem.setIdGame(result);
				betItem.setGameType(gameType);
				
				try {
					float homeRate = Float.parseFloat(homeRateStr);
					betItem.setHomeRate(homeRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("승패 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float awayRate = Float.parseFloat(awayRateStr);
					betItem.setAwayRate(awayRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("승패 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betResult = betDao.addBet(betItem);
				if (betResult < 1) {
					Util.getInstance().alertPage("승패 경기 아이템추가에 실패하였습니다.", response);
					return null;
				}
				
				break;
				
			case 3:
				homeRateStr = request.getParameter("homeRate3").trim();
				tieRateStr = request.getParameter("tieRate3").trim();
				awayRateStr = request.getParameter("awayRate3").trim();
				rateStr = request.getParameter("handiRate3").trim();
				
				if (homeRateStr.indexOf(".") > 0) {
					int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
					if (homeRateLength > 2) {
						Util.getInstance().alertPage("핸디승무패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
					Util.getInstance().alertPage("핸디승무패 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (tieRateStr.indexOf(".") > 0) {
					int tieRateLength = tieRateStr.substring(tieRateStr.indexOf(".") + 1, tieRateStr.length()).length();
					if (tieRateLength > 2) {
						Util.getInstance().alertPage("핸디승무패 무배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (tieRateStr != null && !tieRateStr.equals("") && !checker.isFloat(tieRateStr)) {
					Util.getInstance().alertPage("핸디승무패 무배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (awayRateStr.indexOf(".") > 0) {
					int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
					if (awayRateLength > 2) {
						Util.getInstance().alertPage("핸디승무패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
					Util.getInstance().alertPage("핸디승무패 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (rateStr.indexOf(".") > 0) {
					int handiRateLength = rateStr.substring(rateStr.indexOf(".") + 1, rateStr.length()).length();
					if (handiRateLength > 1) {
						Util.getInstance().alertPage("핸디승무패 핸디 기준점의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (rateStr != null && !rateStr.equals("") && !checker.isFloat2(rateStr)) {
					Util.getInstance().alertPage("핸디승무패 핸디 기준점의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betItem = new BetItem();
				
				betItem.setIdGame(result);
				betItem.setGameType(gameType);
				
				try {
					float homeRate = Float.parseFloat(homeRateStr);
					betItem.setHomeRate(homeRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("핸디승무패 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float tieRate = Float.parseFloat(tieRateStr);
					betItem.setTieRate(tieRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("핸디승무패 무배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float awayRate = Float.parseFloat(awayRateStr);
					betItem.setAwayRate(awayRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("핸디승무패 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float rate = Float.parseFloat(rateStr);
					betItem.setRate(rate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("핸디승무패 핸디/언오버 기준점의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betResult = betDao.addBet(betItem);
				
				if (betResult < 1) {
					Util.getInstance().alertPage("핸디승무패 경기 아이템추가에 실패하였습니다.", response);
					return null;
				}
				
				break;
				
			case 4:
				homeRateStr = request.getParameter("homeRate4").trim();
				awayRateStr = request.getParameter("awayRate4").trim();
				rateStr = request.getParameter("handiRate4").trim();
				
				if (homeRateStr.indexOf(".") > 0) {
					int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
					if (homeRateLength > 2) {
						Util.getInstance().alertPage("핸디승패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
					Util.getInstance().alertPage("핸디승패 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (awayRateStr.indexOf(".") > 0) {
					int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
					if (awayRateLength > 2) {
						Util.getInstance().alertPage("핸디승패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
					Util.getInstance().alertPage("핸디승패 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (rateStr.indexOf(".") > 0) {
					int handiRateLength = rateStr.substring(rateStr.indexOf(".") + 1, rateStr.length()).length();
					if (handiRateLength > 1) {
						Util.getInstance().alertPage("핸디승패 핸디 기준점의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (rateStr != null && !rateStr.equals("") && !checker.isFloat2(rateStr)) {
					Util.getInstance().alertPage("핸디승패 핸디 기준점의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betItem = new BetItem();
				
				betItem.setIdGame(result);
				betItem.setGameType(gameType);
				
				try {
					float homeRate = Float.parseFloat(homeRateStr);
					betItem.setHomeRate(homeRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("핸디승패 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float awayRate = Float.parseFloat(awayRateStr);
					betItem.setAwayRate(awayRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("핸디승패 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float rate = Float.parseFloat(rateStr);
					betItem.setRate(rate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("핸디승패 핸디/언오버 기준점의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betResult = betDao.addBet(betItem);
				
				if (betResult < 1) {
					Util.getInstance().alertPage("핸디승패 경기 아이템추가에 실패하였습니다.", response);
					return null;
				}
				
				break;
				
			case 5:
				homeRateStr = request.getParameter("homeRate5").trim();
				awayRateStr = request.getParameter("awayRate5").trim();
				rateStr = request.getParameter("unoverRate5").trim();
				
				if (homeRateStr.indexOf(".") > 0) {
					int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
					if (homeRateLength > 2) {
						Util.getInstance().alertPage("언오버 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
					Util.getInstance().alertPage("언오버 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (awayRateStr.indexOf(".") > 0) {
					int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
					if (awayRateLength > 2) {
						Util.getInstance().alertPage("언오버 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
					Util.getInstance().alertPage("언오버 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				if (rateStr.indexOf(".") > 0) {
					int unoverRateLength = rateStr.substring(rateStr.indexOf(".") + 1, rateStr.length()).length();
					if (unoverRateLength > 1) {
						Util.getInstance().alertPage("언오버 기준점의 숫자형식을 확인해주세요.", response);
						return null;
					}
				}
				
				if (rateStr != null && !rateStr.equals("") && !checker.isFloat(rateStr)) {
					Util.getInstance().alertPage("언오버 기준점의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betItem = new BetItem();
				
				betItem.setIdGame(result);
				betItem.setGameType(gameType);
				
				try {
					float homeRate = Float.parseFloat(homeRateStr);
					betItem.setHomeRate(homeRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("언오버 홈배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float awayRate = Float.parseFloat(awayRateStr);
					betItem.setAwayRate(awayRate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("언오버 원정배당의 숫자형식을 확인해주세요.", response);
					return null;
				}
				try {
					float rate = Float.parseFloat(rateStr);
					betItem.setRate(rate);
				} catch (NumberFormatException e) {
					Util.getInstance().alertPage("언오버 핸디/언오버 기준점의 숫자형식을 확인해주세요.", response);
					return null;
				}
				
				betResult = betDao.addBet(betItem);
				
				if (betResult < 1) {
					Util.getInstance().alertPage("언오버 경기 아이템추가에 실패하였습니다.", response);
					return null;
				}
				
				break;
				
			case 6:
				betItem = new BetItem();
				
				betItem.setIdGame(result);
				betItem.setGameType(gameType);
				
				betResult = betDao.addBet(betItem);
				
				if (betResult < 1) {
					Util.getInstance().alertPage("기타 경기 아이템추가에 실패하였습니다.", response);
					return null;
				}
				
				break;
			}
		}
		
		if (result > 0) {
			try {
				response.sendRedirect("listGame");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			Util.getInstance().alertPage("추가에 실패하였습니다.", response);
		}
		
		return null;
	}
	
	/** 경기 수정후 리스트 */
	@RequestMapping(value = "editGameOk", method = RequestMethod.POST)
	public String editGameOk(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		String idLeagueStr = request.getParameter("idLeague");
		String leagueInfo = request.getParameter("leagueInfo").trim();
		leagueInfo = leagueInfo.replace("&", "&amp;");
		leagueInfo = leagueInfo.replace("<", "&lt;");
		leagueInfo = leagueInfo.replace(">", "&gt;");
		String idHomeTeamStr = request.getParameter("idHomeTeam");
		String idAwayTeamStr = request.getParameter("idAwayTeam");
		String gameDate = request.getParameter("gameDate").trim();
		String gameInfo = request.getParameter("gameInfo").trim();
		gameInfo = gameInfo.replace("&", "&amp;");
		gameInfo = gameInfo.replace("<", "&lt;");
		gameInfo = gameInfo.replace(">", "&gt;");
		String[] gameTypeArr = request.getParameterValues("gameType");
		
		String idGameStr = request.getParameter("idGame");
		String isDisplayStr = request.getParameter("isDisplay");
		String gameStatusStr = request.getParameter("gameStatus");
		
		if (idLeagueStr == null || idHomeTeamStr == null || idAwayTeamStr == null || gameDate == null || isDisplayStr == null || gameStatusStr == null ||
				idLeagueStr.equals("") || idHomeTeamStr.equals("") || idAwayTeamStr.equals("") || gameDate.equals("") || isDisplayStr.equals("") || gameStatusStr.equals("") ||
				idGameStr == null || idGameStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
			return null;
		}
		
		if (gameTypeArr.length < 1) {
			Util.getInstance().alertPage("경기종류를 최소한 1개이상은 선택해야 합니다.", response);
			return null;
		}
		
		gameDate = gameDate.replace(" ", "");
		gameDate = gameDate.replace("-", "");
		gameDate = gameDate.replace(":", "");
		gameDate += "00";
		
		PatternChecker checker = PatternChecker.getInstance();
		if (gameDate.length() != 14 || !checker.isNum(gameDate)) {
			Util.getInstance().alertPage("경기시간을 yyyy-mm-dd hh:mm 포맷으로 입력해주세요.", response);
			return null;
		}
		
		int idLeague = Integer.parseInt(idLeagueStr);
		int idHomeTeam = Integer.parseInt(idHomeTeamStr);
		int idAwayTeam = Integer.parseInt(idAwayTeamStr);
		
		int isDisplay = Integer.parseInt(isDisplayStr);
		int gameStatus = Integer.parseInt(gameStatusStr);
		int idGame = Integer.parseInt(idGameStr);
		
		GameItem item = new GameItem();
		item.setIdLeague(idLeague);
		item.setIdHomeTeam(idHomeTeam);
		item.setIdAwayTeam(idAwayTeam);
		item.setGameDate(gameDate);
		item.setIsDisplay(isDisplay);
		item.setGameStatus(gameStatus);
		item.setIdGame(idGame);
		
		if (leagueInfo != null && !leagueInfo.equals("")) {
			item.setLeagueInfo(leagueInfo);
		}
		if (gameInfo != null && !gameInfo.equals("")) {
			item.setGameInfo(gameInfo);
		}
		
		int result = 0;
		
		if (gameStatus == 2) {
			String homeScoreStr = request.getParameter("homeScore");
			String awayScoreStr = request.getParameter("awayScore");
			
			if (homeScoreStr == null || awayScoreStr == null || homeScoreStr.equals("") || awayScoreStr.equals("") || !checker.isNum(homeScoreStr) || !checker.isNum(awayScoreStr)) {
				Util.getInstance().alertPage("경기종료의 경기는 홈팀과 원정팀의 점수는 숫자형식으로 필히 입력해야 합니다.", response);
				return null;
			}
			
			int homeScore = Integer.parseInt(homeScoreStr);
			int awayScore = Integer.parseInt(awayScoreStr);
			
			item.setHomeScore(homeScore);
			item.setAwayScore(awayScore);
			
			result = gameDao.editGameResult(item);
			
			List<BetItem> betList = betDao.getBetList(idGame);
			if (betList != null) {
				for (int i=0; i<betList.size(); i++) {
					BetItem betItem = betList.get(i);
					int gameType = betItem.getGameType();
					int editResultBet = 0;
					switch (gameType) {
					
					case 1:
						if (homeScore > awayScore) {
							betItem.setGameResult(1);
						} else if (homeScore < awayScore) {
							betItem.setGameResult(3);
						} else if (homeScore == awayScore) {
							betItem.setGameResult(2);
						}
						editResultBet = betDao.editResultBet(betItem);
						if (editResultBet < 1) {
							Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
							return null;
						}
						break;
						
					case 2:
						if (homeScore > awayScore) {
							betItem.setGameResult(1);
						} else if (homeScore < awayScore) {
							betItem.setGameResult(3);
						}
						editResultBet = betDao.editResultBet(betItem);
						if (editResultBet < 1) {
							Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
							return null;
						}
						break;
						
					case 3:
						if ((homeScore + betItem.getRate()) > awayScore) {
							betItem.setGameResult(4);
						} else if ((homeScore + betItem.getRate()) < awayScore) {
							betItem.setGameResult(6);
						} else if ((homeScore + betItem.getRate()) == awayScore) {
							betItem.setGameResult(5);
						}
						editResultBet = betDao.editResultBet(betItem);
						if (editResultBet < 1) {
							Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
							return null;
						}
						break;
						
					case 4:
						if ((homeScore + betItem.getRate()) > awayScore) {
							betItem.setGameResult(4);
						} else if ((homeScore + betItem.getRate()) < awayScore) {
							betItem.setGameResult(6);
						}
						editResultBet = betDao.editResultBet(betItem);
						if (editResultBet < 1) {
							Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
							return null;
						}
						break;
						
					case 5:
						if ((homeScore + awayScore) < betItem.getRate()) {
							betItem.setGameResult(7);
						} else if ((homeScore + awayScore) > betItem.getRate()) {
							betItem.setGameResult(8);
						}
						editResultBet = betDao.editResultBet(betItem);
						if (editResultBet < 1) {
							Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
							return null;
						}
						model.addAttribute("gameType5", betItem);
						break;
						
					case 6:
						betItem.setGameResult(0);
						editResultBet = betDao.editResultBet(betItem);
						if (editResultBet < 1) {
							Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
							return null;
						}
						model.addAttribute("gameType5", betItem);
						break;
					}
				}
			}
		} else {
			result = gameDao.editGame(item);
		}
		
		if (result < 1) {
			Util.getInstance().alertPage("수정에 실패하였습니다.", response);
			return null;
		}
		
		List<BetItem> betList = betDao.getBetList(idGame);
		for (int i=1; i<7; i++) {
			
			boolean isAdd = false;
			boolean isEdit = false;
			boolean isDel = false;
			
			int gameType = 0;
			if (gameTypeArr != null) {
				for (int j=0; j<gameTypeArr.length; j++) {
					try {
						if (Integer.parseInt(gameTypeArr[j]) == i) {
							gameType = i;
						}
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("파라미터 형식이 잘못되었습니다.", response);
						return null;
					}
				}
			}
			
			int getGameType = 0;
			if (betList != null) {
				for (int j=0; j<betList.size(); j++) {
					if (betList.get(j).getGameType() == i) {
						getGameType = i;
					}
				}
			}
			
			if (gameType > 0 && gameType == getGameType) {
				isEdit = true;
			} else if (gameType > 0 && getGameType == 0) {
				isAdd = true;
			} else if (getGameType > 0 && gameType == 0) {
				isDel = true;
			}
			
			String homeRateStr = null, tieRateStr = null, awayRateStr = null, rateStr = null;
			BetItem betItem = null;
			int betResult = 0;
			if (isAdd || isEdit) {
				switch (i) {
				case 1:
					homeRateStr = request.getParameter("homeRate1").trim();
					tieRateStr = request.getParameter("tieRate1").trim();
					awayRateStr = request.getParameter("awayRate1").trim();
					
					if (homeRateStr.indexOf(".") > 0) {
						int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
						if (homeRateLength > 2) {
							Util.getInstance().alertPage("승무패 홈배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
						Util.getInstance().alertPage("승무패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (tieRateStr.indexOf(".") > 0) {
						int tieRateLength = tieRateStr.substring(tieRateStr.indexOf(".") + 1, tieRateStr.length()).length();
						if (tieRateLength > 2) {
							Util.getInstance().alertPage("승무패 무배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (tieRateStr != null && !tieRateStr.equals("") && !checker.isFloat(tieRateStr)) {
						Util.getInstance().alertPage("승무패 무배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (awayRateStr.indexOf(".") > 0) {
						int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
						if (awayRateLength > 2) {
							Util.getInstance().alertPage("승무패 원정배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
						Util.getInstance().alertPage("승무패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					betItem = new BetItem();
					
					betItem.setIdGame(idGame);
					betItem.setGameType(i);
					
					try {
						float homeRate = Float.parseFloat(homeRateStr);
						betItem.setHomeRate(homeRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("승무패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float tieRate = Float.parseFloat(tieRateStr);
						betItem.setTieRate(tieRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("승무패 무배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float awayRate = Float.parseFloat(awayRateStr);
						betItem.setAwayRate(awayRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("승무패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (isAdd) {
						betResult = betDao.addBet(betItem);
					} else if (isEdit) {
						betResult = betDao.editBet(betItem);
					}
					
					
					if (betResult < 1) {
						Util.getInstance().alertPage("승무패 경기 아이템수정에 실패하였습니다.", response);
						return null;
					}
					
					break;
					
				case 2:
					homeRateStr = request.getParameter("homeRate2").trim();
					awayRateStr = request.getParameter("awayRate2").trim();
					
					if (homeRateStr.indexOf(".") > 0) {
						int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
						if (homeRateLength > 2) {
							Util.getInstance().alertPage("승패 홈배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
						Util.getInstance().alertPage("승패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (awayRateStr.indexOf(".") > 0) {
						int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
						if (awayRateLength > 2) {
							Util.getInstance().alertPage("승패 원정배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
						Util.getInstance().alertPage("승패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					betItem = new BetItem();
					
					betItem.setIdGame(idGame);
					betItem.setGameType(i);
					
					try {
						float homeRate = Float.parseFloat(homeRateStr);
						betItem.setHomeRate(homeRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("승패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float awayRate = Float.parseFloat(awayRateStr);
						betItem.setAwayRate(awayRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("승패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (isAdd) {
						betResult = betDao.addBet(betItem);
					} else if (isEdit) {
						betResult = betDao.editBet(betItem);
					}
					
					if (betResult < 1) {
						Util.getInstance().alertPage("승패 경기 아이템수정에 실패하였습니다.", response);
						return null;
					}
					
					break;
					
				case 3:
					homeRateStr = request.getParameter("homeRate3").trim();
					tieRateStr = request.getParameter("tieRate3").trim();
					awayRateStr = request.getParameter("awayRate3").trim();
					rateStr = request.getParameter("handiRate3").trim();
					
					if (homeRateStr.indexOf(".") > 0) {
						int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
						if (homeRateLength > 2) {
							Util.getInstance().alertPage("핸디승무패 홈배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
						Util.getInstance().alertPage("핸디승무패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (tieRateStr.indexOf(".") > 0) {
						int tieRateLength = tieRateStr.substring(tieRateStr.indexOf(".") + 1, tieRateStr.length()).length();
						if (tieRateLength > 2) {
							Util.getInstance().alertPage("핸디승무패 무배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (tieRateStr != null && !tieRateStr.equals("") && !checker.isFloat(tieRateStr)) {
						Util.getInstance().alertPage("핸디승무패 무배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (awayRateStr.indexOf(".") > 0) {
						int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
						if (awayRateLength > 2) {
							Util.getInstance().alertPage("핸디승무패 원정배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
						Util.getInstance().alertPage("핸디승무패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (rateStr.indexOf(".") > 0) {
						int handiRateLength = rateStr.substring(rateStr.indexOf(".") + 1, rateStr.length()).length();
						if (handiRateLength > 1) {
							Util.getInstance().alertPage("핸디승무패 핸디 기준점의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (rateStr != null && !rateStr.equals("") && !checker.isFloat2(rateStr)) {
						Util.getInstance().alertPage("핸디승무패 핸디 기준점의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					betItem = new BetItem();
					
					betItem.setIdGame(idGame);
					betItem.setGameType(i);
					
					try {
						float homeRate = Float.parseFloat(homeRateStr);
						betItem.setHomeRate(homeRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("핸디승무패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float tieRate = Float.parseFloat(tieRateStr);
						betItem.setTieRate(tieRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("핸디승무패 무배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float awayRate = Float.parseFloat(awayRateStr);
						betItem.setAwayRate(awayRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("핸디승무패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float rate = Float.parseFloat(rateStr);
						betItem.setRate(rate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("핸디승무패 핸디/언오버 기준점의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (isAdd) {
						betResult = betDao.addBet(betItem);
					} else if (isEdit) {
						betResult = betDao.editBet(betItem);
					}
					
					if (betResult < 1) {
						Util.getInstance().alertPage("핸디승무패 경기 아이템수정에 실패하였습니다.", response);
						return null;
					}
					
					break;
					
				case 4:
					homeRateStr = request.getParameter("homeRate4").trim();
					awayRateStr = request.getParameter("awayRate4").trim();
					rateStr = request.getParameter("handiRate4").trim();
					
					if (homeRateStr.indexOf(".") > 0) {
						int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
						if (homeRateLength > 2) {
							Util.getInstance().alertPage("핸디승패 홈배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
						Util.getInstance().alertPage("핸디승패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (awayRateStr.indexOf(".") > 0) {
						int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
						if (awayRateLength > 2) {
							Util.getInstance().alertPage("핸디승패 원정배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
						Util.getInstance().alertPage("핸디승패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (rateStr.indexOf(".") > 0) {
						int handiRateLength = rateStr.substring(rateStr.indexOf(".") + 1, rateStr.length()).length();
						if (handiRateLength > 1) {
							Util.getInstance().alertPage("핸디승패 핸디 기준점의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (rateStr != null && !rateStr.equals("") && !checker.isFloat2(rateStr)) {
						Util.getInstance().alertPage("핸디승패 핸디 기준점의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					betItem = new BetItem();
					
					betItem.setIdGame(idGame);
					betItem.setGameType(i);
					
					try {
						float homeRate = Float.parseFloat(homeRateStr);
						betItem.setHomeRate(homeRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("핸디승패 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float awayRate = Float.parseFloat(awayRateStr);
						betItem.setAwayRate(awayRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("핸디승패 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float rate = Float.parseFloat(rateStr);
						betItem.setRate(rate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("핸디승패 핸디/언오버 기준점의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (isAdd) {
						betResult = betDao.addBet(betItem);
					} else if (isEdit) {
						betResult = betDao.editBet(betItem);
					}
					
					if (betResult < 1) {
						Util.getInstance().alertPage("핸디승패 경기 아이템추가에 실패하였습니다.", response);
						return null;
					}
					
					break;
					
				case 5:
					homeRateStr = request.getParameter("homeRate5").trim();
					awayRateStr = request.getParameter("awayRate5").trim();
					rateStr = request.getParameter("unoverRate5").trim();
					
					if (homeRateStr.indexOf(".") > 0) {
						int homeRateLength = homeRateStr.substring(homeRateStr.indexOf(".") + 1, homeRateStr.length()).length();
						if (homeRateLength > 2) {
							Util.getInstance().alertPage("언오버 홈배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (homeRateStr != null && !homeRateStr.equals("") && !checker.isFloat(homeRateStr)) {
						Util.getInstance().alertPage("언오버 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (awayRateStr.indexOf(".") > 0) {
						int awayRateLength = awayRateStr.substring(awayRateStr.indexOf(".") + 1, awayRateStr.length()).length();
						if (awayRateLength > 2) {
							Util.getInstance().alertPage("언오버 원정배당의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (awayRateStr != null && !awayRateStr.equals("") && !checker.isFloat(awayRateStr)) {
						Util.getInstance().alertPage("언오버 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (rateStr.indexOf(".") > 0) {
						int unoverRateLength = rateStr.substring(rateStr.indexOf(".") + 1, rateStr.length()).length();
						if (unoverRateLength > 1) {
							Util.getInstance().alertPage("언오버 기준점의 숫자형식을 확인해주세요.", response);
							return null;
						}
					}
					
					if (rateStr != null && !rateStr.equals("") && !checker.isFloat(rateStr)) {
						Util.getInstance().alertPage("언오버 기준점의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					betItem = new BetItem();
					
					betItem.setIdGame(idGame);
					betItem.setGameType(i);
					
					try {
						float homeRate = Float.parseFloat(homeRateStr);
						betItem.setHomeRate(homeRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("언오버 홈배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float awayRate = Float.parseFloat(awayRateStr);
						betItem.setAwayRate(awayRate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("언오버 원정배당의 숫자형식을 확인해주세요.", response);
						return null;
					}
					try {
						float rate = Float.parseFloat(rateStr);
						betItem.setRate(rate);
					} catch (NumberFormatException e) {
						Util.getInstance().alertPage("언오버 핸디/언오버 기준점의 숫자형식을 확인해주세요.", response);
						return null;
					}
					
					if (isAdd) {
						betResult = betDao.addBet(betItem);
					} else if (isEdit) {
						betResult = betDao.editBet(betItem);
					}
					
					if (betResult < 1) {
						Util.getInstance().alertPage("언오버 경기 아이템수정에 실패하였습니다.", response);
						return null;
					}
					
					break;
					
				case 6:
					betItem = new BetItem();
					
					betItem.setIdGame(idGame);
					betItem.setGameType(i);
					
					if (isAdd) {
						betResult = betDao.addBet(betItem);
					} else if (isEdit) {
						betResult = betDao.editBet(betItem);
					}
					
					if (betResult < 1) {
						Util.getInstance().alertPage("기타 경기 아이템수정에 실패하였습니다.", response);
						return null;
					}
					
					break;
				}
			} else if (isDel) {
				betItem = new BetItem();
				
				betItem.setIdGame(idGame);
				betItem.setGameType(i);
				
				betResult = betDao.delBet(betItem);
				
				if (betResult < 1) {
					Util.getInstance().alertPage("기타 경기 아이템삭제에 실패하였습니다.", response);
					return null;
				}
			}
			
		}
		
		int page = 1;
		String pageStr = request.getParameter("page");
		
		if (pageStr != null) {
			page = Integer.parseInt(pageStr);
		}
		
		String where = request.getParameter("where");
		boolean whereCheck = false;
		
		String[] arr = where.substring(1, where.length()).split("&");
		for (int i=0; i<arr.length; i++) {
			String[] temp = arr[i].split("=");
			if (temp[0].equals("regDate1")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("regDate2")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("sport")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("league")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("gameStatus")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("homeTeam")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("homeLeague")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("homeSport")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("awayTeam")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("awayLeague")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("awaySport")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			}
		}
		
		if (result > 0) {
			try {
				if (whereCheck) {
					response.sendRedirect("listGame?page=" + page + "&where=" + where);
				} else {
					response.sendRedirect("listGame?page=" + page);
				}
			} catch (IOException e) {
				Util.getInstance().alertPage("수정에 실패하였습니다.", response);
				e.printStackTrace();
			}
		} else {
			Util.getInstance().alertPage("수정에 실패하였습니다.", response);
			return null;
		}
		
		return null;
	}
	
	/** 경기 검색 */
	@RequestMapping(value = "searchGame", method = RequestMethod.GET)
	public String searchGame(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		String[] where = where(model, request, response);
		
		if (where == null) {
			return null;
		}
		
		int page = 1;
		int size = 10;
		String pageStr = request.getParameter("page");
		
		if (pageStr != null) {
			page = Integer.parseInt(pageStr);
		}
		
		model.addAttribute("sportList", sportDao.getSportList("ASC"));
		model.addAttribute("toggle", commonDao.getCommonText("경기검색"));
		model.addAttribute("displayCount", gameDao.getDisplayCount(where[0]));
		model.addAttribute("unDisplayCount", gameDao.getUnDisplayCount(where[0]));
		model.addAttribute("list", gameDao.getGameList(page, size, where[0], "g.idGame DESC"));
		model.addAttribute("page", PageHandler.getInstance());
		model.addAttribute("now", DateTime.getInstance().getNowDateTimeString());
		model.addAttribute("where", where[1]);
		
		return "game/listGame";
	}
	
	/** 경기 조회 */
	@RequestMapping(value = "viewGame", method = RequestMethod.GET)
	public String viewGame(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		int page = 1;
		String idStr = request.getParameter("id");
		String pageStr = request.getParameter("page");
		
		String[] where = where(model, request, response);
		
		if (idStr == null || idStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
			return null;
		}
		
		int id = Integer.parseInt(idStr);
		if (pageStr != null) {
			page = Integer.parseInt(pageStr);
		}
		
		GameItem item = new GameItem();
		item.setIdGame(id);
		
		GameItem result = gameDao.getGame(item);
		model.addAttribute("item", result);
		model.addAttribute("page", page);
		model.addAttribute("where", where[1]);
		
		model.addAttribute("sportList", sportDao.getSportList("ASC"));
		
		List<BetItem> betList = betDao.getBetList(id);
		if (betList != null) {
			for (int i=0; i<betList.size(); i++) {
				BetItem betItem = betList.get(i);
				int gameType = betItem.getGameType();
				switch (gameType) {
				case 1:
					model.addAttribute("gameType1", betItem);
					break;
				case 2:
					model.addAttribute("gameType2", betItem);
					break;
				case 3:
					model.addAttribute("gameType3", betItem);
					break;
				case 4:
					model.addAttribute("gameType4", betItem);
					break;
				case 5:
					model.addAttribute("gameType5", betItem);
					break;
				case 6:
					model.addAttribute("gameType6", betItem);
					break;
				}
			}
		}
		
		return "game/viewGame";
	}
	
	/** 경기 결과등록 */
	@RequestMapping(value = "resultGame", method = RequestMethod.GET)
	public String resultGame(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		int page = 1;
		int size = 10;
		String pageStr = request.getParameter("page");
		
		if (pageStr != null) {
			page = Integer.parseInt(pageStr);
		}
		
		model.addAttribute("list", gameDao.getGameList(page, size, " AND g.isDisplay=1 AND g.gameStatus=1 AND DATE_FORMAT(now(), '%Y%m%d%H%i%s') >= g.gameDate", "g.idGame DESC"));
		model.addAttribute("page", PageHandler.getInstance());
		
		return "game/resultGame";
	}
	
	/** 경기 결과등록 처리후 리스트 */
	@RequestMapping(value = "resultGameOk", method = RequestMethod.GET)
	public String resultGameOk(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		String pageStr = request.getParameter("page");
		String idGameStr = request.getParameter("idGame");
		String homeScoreStr = request.getParameter("homeScore" + idGameStr);
		String awayScoreStr = request.getParameter("awayScore" + idGameStr);
		
		if (pageStr == null || pageStr.equals("") || idGameStr == null || idGameStr.equals("") || homeScoreStr == null || homeScoreStr.equals("") ||
				awayScoreStr == null || awayScoreStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
			return null;
		}
		
		PatternChecker checker = PatternChecker.getInstance();
		if (!checker.isNum(pageStr) || !checker.isNum(idGameStr) || !checker.isNum(homeScoreStr) || !checker.isNum(awayScoreStr)) {
			Util.getInstance().alertPage("숫자형식인지 다시 확인해 주세요.", response);
			return null;
		}
		
		int page = Integer.parseInt(pageStr);
		int idGame = Integer.parseInt(idGameStr);
		int homeScore = Integer.parseInt(homeScoreStr);
		int awayScore = Integer.parseInt(awayScoreStr);
		
		GameItem item = new GameItem();
		item.setIdGame(idGame);
		item.setHomeScore(homeScore);
		item.setAwayScore(awayScore);
		
		int result = gameDao.gameResult(item);
		
		List<BetItem> betList = betDao.getBetList(idGame);
		if (betList != null) {
			for (int i=0; i<betList.size(); i++) {
				BetItem betItem = betList.get(i);
				int gameType = betItem.getGameType();
				int editResultBet = 0;
				switch (gameType) {
				
				case 1:
					if (homeScore > awayScore) {
						betItem.setGameResult(1);
					} else if (homeScore < awayScore) {
						betItem.setGameResult(3);
					} else if (homeScore == awayScore) {
						betItem.setGameResult(2);
					}
					editResultBet = betDao.editResultBet(betItem);
					if (editResultBet < 1) {
						Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
						return null;
					}
					break;
					
				case 2:
					if (homeScore > awayScore) {
						betItem.setGameResult(1);
					} else if (homeScore < awayScore) {
						betItem.setGameResult(3);
					}
					editResultBet = betDao.editResultBet(betItem);
					if (editResultBet < 1) {
						Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
						return null;
					}
					break;
					
				case 3:
					if ((homeScore + betItem.getRate()) > awayScore) {
						betItem.setGameResult(4);
					} else if ((homeScore + betItem.getRate()) < awayScore) {
						betItem.setGameResult(6);
					} else if ((homeScore + betItem.getRate()) == awayScore) {
						betItem.setGameResult(5);
					}
					editResultBet = betDao.editResultBet(betItem);
					if (editResultBet < 1) {
						Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
						return null;
					}
					break;
					
				case 4:
					if ((homeScore + betItem.getRate()) > awayScore) {
						betItem.setGameResult(4);
					} else if ((homeScore + betItem.getRate()) < awayScore) {
						betItem.setGameResult(6);
					}
					editResultBet = betDao.editResultBet(betItem);
					if (editResultBet < 1) {
						Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
						return null;
					}
					break;
					
				case 5:
					if ((homeScore + awayScore) < betItem.getRate()) {
						betItem.setGameResult(7);
					} else if ((homeScore + awayScore) > betItem.getRate()) {
						betItem.setGameResult(8);
					}
					editResultBet = betDao.editResultBet(betItem);
					if (editResultBet < 1) {
						Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
						return null;
					}
					model.addAttribute("gameType5", betItem);
					break;
					
				case 6:
					betItem.setGameResult(0);
					editResultBet = betDao.editResultBet(betItem);
					if (editResultBet < 1) {
						Util.getInstance().alertPage("경기마감 처리에 실패했습니다.", response);
						return null;
					}
					model.addAttribute("gameType5", betItem);
					break;
				}
			}
		}
		
		if (result > 0) {
			
			String html = "<!doctype html>";
			html += "<head>";
			html += "<meta charset='utf-8'>";
			html += "<script>";
			html += "alert('정상적으로 수정되었습니다.');";
			html += "location.replace('resultGame?page=" + page + "');";
			html += "</script>";
			html += "</head>";
			html += "</html>";
			
			try {
				response.setCharacterEncoding("utf-8");
				PrintWriter out = response.getWriter();
				out.print(html);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			Util.getInstance().alertPage("경기결과 수정에 실패하였습니다.", response);
		}
		
		return null;
	}
	
	public String[] where(Model model, HttpServletRequest request, HttpServletResponse response) {
		
		String where = null;
		
		String sport = request.getParameter("sport");
		if (sport != null && !sport.equals("default") && !sport.equals("null") && !sport.equals("")) {
			model.addAttribute("sport", sport);
			if (where == null) where = "";
			where += " AND l.idSport=" + sport;
		}
		
		String league = request.getParameter("league");
		if (league != null && !league.equals("default") && !league.equals("null") && !league.equals("")) {
			model.addAttribute("league", league);
			if (where == null) where = "";
			where += " AND l.idLeague=" + league;
		}
		
		PatternChecker checker = PatternChecker.getInstance();
		String regDate1 = request.getParameter("regDate1");
		String regDate2 = request.getParameter("regDate2");
		String regDate1Str = null, regDate2Str = null;
		if (regDate1 != null && !regDate1.equals("") && !regDate1.equals("null")) {
			regDate1Str = regDate1.replace("-", "");
			if (regDate1Str.length() != 8 || !checker.isNum(regDate1Str)) {
				Util.getInstance().alertPage("등록일 시작을 yyyy-mm-dd 포맷으로 입력해주세요.", response);
				return null;
			}
		}
		if (regDate2 != null && !regDate2.equals("") && !regDate2.equals("null")) {
			regDate2Str = regDate2.replace("-", "");
			if (regDate2Str.length() != 8 || !checker.isNum(regDate2Str)) {
				Util.getInstance().alertPage("등록일 끝을 yyyy-mm-dd 포맷으로 입력해주세요.", response);
				return null;
			}
		}
		
		if (regDate1Str != null && regDate1Str.length() == 8 && checker.isNum(regDate1Str) && regDate2Str != null && regDate2Str.length() == 8 && checker.isNum(regDate2Str)) {
			if (where == null) where = "";
			model.addAttribute("regDate1", regDate1);
			model.addAttribute("regDate2", regDate2);
			where += " AND g.regDate BETWEEN " + regDate1Str + "000000 AND " + regDate2Str + "999999";
		} else if (regDate1Str != null && regDate1Str.length() == 8 && checker.isNum(regDate1Str)) {
			if (where == null) where = "";
			model.addAttribute("regDate1", regDate1);
			where += " AND g.regDate > " + regDate1Str + "000000";
		} else if (regDate2Str != null && regDate2Str.length() == 8 && checker.isNum(regDate2Str)) {
			if (where == null) where = "";
			model.addAttribute("regDate2", regDate2);
			where += " AND g.regDate < " + regDate2Str + "999999";
		}
		
		String gameStatus = request.getParameter("gameStatus");
		if (gameStatus != null && !gameStatus.equals("default") && !gameStatus.equals("null") && !gameStatus.equals("")) {
			model.addAttribute("gameStatus", gameStatus);
			if (where == null) where = "";
			if (gameStatus.equals("0")) {
				where += " AND g.gameStatus=1 AND DATE_FORMAT(now(), '%Y%m%d%H%i%s') < g.gameDate";
			} else if (gameStatus.equals("1")) {
				where += " AND g.gameStatus=1 AND DATE_FORMAT(now(), '%Y%m%d%H%i%s') >= g.gameDate";
			} else if (gameStatus.equals("2") || gameStatus.equals("3")){
				where += " AND g.gameStatus=" + gameStatus;
			}
		}
		
		String gameDate1 = request.getParameter("gameDate1");
		String gameDate2 = request.getParameter("gameDate2");
		String gameDate1Str = null, gameDate2Str = null;
		if (gameDate1 != null && !gameDate1.equals("") && !gameDate1.equals("null")) {
			gameDate1Str = gameDate1.replace(" ", "");
			gameDate1Str = gameDate1Str.replace("-", "");
			gameDate1Str = gameDate1Str.replace(":", "");
			gameDate1Str += "00";
			
			if (gameDate1Str.length() != 14 || !checker.isNum(gameDate1Str)) {
				Util.getInstance().alertPage("경기시간 시작을 yyyy-mm-dd hh:mm 포맷으로 입력해주세요.", response);
				return null;
			}
		}
		if (gameDate2 != null && !gameDate2.equals("") && !gameDate2.equals("null")) {
			gameDate2Str = gameDate2.replace(" ", "");
			gameDate2Str = gameDate2Str.replace("-", "");
			gameDate2Str = gameDate2Str.replace(":", "");
			gameDate2Str += "00";
			
			if (gameDate2Str.length() != 14 || !checker.isNum(gameDate2Str)) {
				Util.getInstance().alertPage("경기시간 끝을 yyyy-mm-dd hh:mm 포맷으로 입력해주세요.", response);
				return null;
			}
		}
		
		if (gameDate1Str != null && gameDate1Str.length() == 14 && checker.isNum(gameDate1Str) && gameDate2Str != null && gameDate2Str.length() == 14 && checker.isNum(gameDate2Str)) {
			if (where == null) where = "";
			model.addAttribute("gameDate1", gameDate1);
			model.addAttribute("gameDate2", gameDate2);
			where += " AND g.gameDate BETWEEN " + gameDate1Str + " AND " + gameDate2Str;
		} else if (gameDate1Str != null && gameDate1Str.length() == 14 && checker.isNum(gameDate1Str)) {
			if (where == null) where = "";
			model.addAttribute("gameDate1", gameDate1);
			where += " AND g.gameDate >= " + gameDate1Str;
		} else if (gameDate2Str != null && gameDate2Str.length() == 14 && checker.isNum(gameDate2Str)) {
			if (where == null) where = "";
			model.addAttribute("gameDate2", gameDate2);
			where += " AND g.gameDate <= " + gameDate2Str;
		}
		
		String homeTeam = request.getParameter("homeTeam");
		String homeLeague = request.getParameter("homeLeague");
		String homeSport = request.getParameter("homeSport");
		if (homeTeam != null && !homeTeam.equals("default") && !homeTeam.equals("null") && !homeTeam.equals("")) {
			model.addAttribute("homeTeam", homeTeam);
			model.addAttribute("homeLeague", homeLeague);
			model.addAttribute("homeSport", homeSport);
			if (where == null) where = "";
			where += " AND t1.idTeam=" + homeTeam;
		} else if (homeLeague != null && !homeLeague.equals("default") && !homeLeague.equals("null") && !homeLeague.equals("")) {
			model.addAttribute("homeLeague", homeLeague);
			model.addAttribute("homeSport", homeSport);
			if (where == null) where = "";
			where += " AND t1.idLeague=" + homeLeague;
		} else if (homeSport != null && !homeSport.equals("default") && !homeSport.equals("null") && !homeSport.equals("")) {
			model.addAttribute("homeSport", homeSport);
			if (where == null) where = "";
			where += " AND l1.idSport=" + homeSport;
		}
		
		String awayTeam = request.getParameter("awayTeam");
		String awayLeague = request.getParameter("awayLeague");
		String awaySport = request.getParameter("awaySport");
		if (awayTeam != null && !awayTeam.equals("default") && !awayTeam.equals("null") && !awayTeam.equals("")) {
			model.addAttribute("awayTeam", awayTeam);
			model.addAttribute("awayLeague", awayLeague);
			model.addAttribute("awaySport", awaySport);
			if (where == null) where = "";
			where += " AND t2.idTeam=" + awayTeam;
		} else if (awayLeague != null && !awayLeague.equals("default") && !awayLeague.equals("null") && !awayLeague.equals("")) {
			model.addAttribute("awayLeague", awayLeague);
			model.addAttribute("awaySport", awaySport);
			if (where == null) where = "";
			where += " AND t2.idLeague=" + awayLeague;
		} else if (awaySport != null && !awaySport.equals("default") && !awaySport.equals("null") && !awaySport.equals("")) {
			model.addAttribute("awaySport", awaySport);
			if (where == null) where = "";
			where += " AND l2.idSport=" + awaySport;
		}
		
		String result[] = new String[2];
		result[0] = where;
		result[1] = "&regDate1=" + regDate1 + "&regDate2=" + regDate2 + "&sport=" + sport + "&league=" + league + "&gameStatus=" + gameStatus +
				"&gameDate1=" + gameDate1 + "&gameDate2=" + gameDate2 + "&homeTeam=" + homeTeam + "&homeLeague=" + homeLeague + "&homeSport=" + homeSport +
				"&awayTeam=" + awayTeam + "&awayLeague=" + awayLeague + "&awaySport=" + awaySport;
		
		return result;
	}

}
